﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Server.Entity
{
    public class DbContext
    {
        private const string DatabaseFileName = "database.sqlite";

        static DbContext()
        {
            var dbFileInfo = new FileInfo(DatabaseFileName);
            if (!dbFileInfo.Exists)
            {
                InitTables(dbFileInfo);
            }
        }

        private static SqlSugarClient Db =>
            new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = $"Data Source={DatabaseFileName};Version=3;",
                DbType = DbType.Sqlite,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            });

        private static void InitTables(FileInfo dbFileInfo)
        {
            File.Create(dbFileInfo.FullName).Dispose();
            var dbTypes = new List<Type>();
            Assembly.GetAssembly(typeof(DbContext)).GetTypes()
                .ToList()
                .ForEach(m =>
                {
                    if (m.IsClass && !m.IsAbstract && m.IsSubclassOf(typeof(BaseTable)))
                    {
                        dbTypes.Add(m);
                    }
                });

            Db.CodeFirst.InitTables(dbTypes.ToArray());
        }

        public static void Execute(Action<SqlSugarClient> action)
        {
            action(Db);
        }

        public static TResult Execute<TResult>(Func<SqlSugarClient, TResult> func)
        {
            return func(Db);
        }
    }
}
